package handler

import (
	"github.com/gin-gonic/gin"
	"schools/api-getaway/api/register"
	"schools/api-getaway/initlist/model"
	"schools/api-getaway/inits/mysql"
	"schools/api-getaway/internal/dao"
	"strconv"
)

type Res struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func Login(r *gin.Context) {
	var req register.User
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}
	user := model.User{}
	if err = dao.FindUsername(&user, req.Username); err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "用户查询失败",
			Data:    nil,
		})
		return
	}
	if user.ID == 0 {
		r.JSON(400, &Res{
			Code:    400,
			Message: "用户不存在",
			Data:    nil,
		})
		return
	}
	if user.Password != req.Password {
		r.JSON(400, &Res{
			Code:    400,
			Message: "密码错误",
			Data:    nil,
		})
		return
	}
	r.JSON(200, &Res{
		Code:    200,
		Message: "登录成功",
		Data:    user.ID,
	})
}

func SchoolAdd(r *gin.Context) {
	var req register.School
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}
	school := model.School{
		Name:    req.Name,
		Address: req.Address,
		Img:     req.Img,
		Mobile:  req.Mobile,
	}
	mysql.DB.Debug().Create(&school)
	r.JSON(200, &Res{
		Code:    200,
		Message: "学校信息添加成功",
		Data:    school,
	})
}

func SchoolList(r *gin.Context) {
	var req register.Fen
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	page, _ := strconv.Atoi(strconv.Itoa(req.Page))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(strconv.Itoa(req.Size))
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var all []model.School
	mysql.DB.Debug().Offset(offset).Limit(pageSize).Order("create_at desc").Find(&all)
	r.JSON(200, &Res{
		Code:    200,
		Message: "列表展示成功",
		Data:    all,
	})
}

func UserList(r *gin.Context) {
	var req register.User
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	var all []model.User
	mysql.DB.Debug().Find(&all)
	r.JSON(200, &Res{
		Code:    200,
		Message: "账号列表展示成功",
		Data:    all,
	})
}
